using System;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Text;
using System.Globalization;
using System.Resources;
using System.Reflection;
using System.Threading;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Publishing;
using Microsoft.SharePoint.Publishing.WebControls;
using Microsoft.SharePoint.Publishing.Internal;
using Microsoft.SharePoint.Publishing.Internal.WebControls;
using Microsoft.SharePoint.Publishing.Internal.CodeBehind;
using Microsoft.Office.Server.Utilities;

namespace Components2.CustomAdmin {

    public class AdminAreaChromeSettingsPage : BasePublishingPage {

        public static readonly Guid FEATURE_CustomAdminMasterPage = new Guid("66EF0C10-03DB-40fb-B9F8-6F1E7B85A9F7");

        // Fields
        private DropDownListWithDetails.ItemInfo[] dataList;
        protected RadioButtonWithChild inheritSystemMasterPageRadioButton;
        protected Control webapplicationWarning;
        protected Control invalidSystemMasterPageWarning;
        protected DropDownListWithDetails masterPageSelectionControl;
        protected RadioButtonWithChild selectSystemMasterPageRadioButton;
        protected DropDownListWithDetails systemMasterPageSelectionControl;

        // Methods
        private void ApplyPropertyChanges(PublishingWeb area) {
            this.ApplyPropertyChanges(area, CustomMasterPageModule.CUSTOM_MASTER_PAGE, this.inheritSystemMasterPageRadioButton, this.systemMasterPageSelectionControl.SelectedValue);
        }

        private void ApplyPropertyChanges(PublishingWeb area, string key, RadioButtonWithChild inheritRadioButton, string selectedValue) {
            if (inheritRadioButton.Checked) {
                selectedValue = string.Empty;
            }
            string currentValue = null;
            if (area.Web.Properties.ContainsKey(key)) {
                currentValue = area.Web.Properties[key];
            }
            bool flag = false;
            if (currentValue == null && !string.IsNullOrEmpty(selectedValue)) { //1st set
                flag = true;
            }
            if (!string.IsNullOrEmpty(currentValue) && !string.IsNullOrEmpty(selectedValue)) { //change
                if (!string.Equals(currentValue, selectedValue, StringComparison.OrdinalIgnoreCase)) {
                    flag = true;
                }
            }
            if (!string.IsNullOrEmpty(currentValue) && string.IsNullOrEmpty(selectedValue)) { //clear
                flag = true;
            }
            if (currentValue == string.Empty && !string.IsNullOrEmpty(selectedValue)) { //set from clear
                flag = true;
            }
            if (flag) {
                if (currentValue != null) {
                    area.Web.Properties[key] = selectedValue;
                } else {
                    area.Web.Properties.Add(key, selectedValue);
                }
                area.Web.Properties.Update();
            }
        }

        protected void ButtonSaveSettings_Click(object sender, EventArgs e) {
            if (!SPUtility.ValidateFormDigest()) {
                throw new InvalidOperationException();
            }
            PublishingWeb currentPublishingWeb = this.CurrentPublishingWeb;
            if (this.FinishUrl == null) {
                this.FinishUrl = this.CurrentPublishingWeb.Url;
            }
            //note: removed check for permissions as must have ManageWeb only (no need to RunWithElevatedPrivileges)
            this.ApplyPropertyChanges(currentPublishingWeb);
            SPUtility.Redirect(this.FinishUrl, SPRedirectFlags.UseSource, this.Context);
        }

        private string GetPublishingResourcesString(string resourceName) {
            Assembly resourceAssembly = Assembly.Load("Microsoft.SharePoint.Publishing.intl, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c");
            ResourceManager resourceManager = new ResourceManager("Microsoft.SharePoint.Publishing.Strings", resourceAssembly);
            ResourceManager resourceBrandStringManager = new ResourceManager("Microsoft.SharePoint.Publishing.BrandStrings", resourceAssembly);
            return resourceManager.GetString(resourceName, Thread.CurrentThread.CurrentUICulture);
        }

        private void InitDataList() {
            SPListItemCollection masterPageLayouts = new PublishingSite(base.Site).GetMasterPageLayouts();
            if (masterPageLayouts.Count <= 0) {
                throw new SPException(GetPublishingResourcesString("ErrorCannotFindPublishingMasterPages"));
            }
            this.dataList = new DropDownListWithDetails.ItemInfo[masterPageLayouts.Count];
            int index = 0;

            foreach (SPListItem item in masterPageLayouts) {
                PageLayout layout = new PageLayout(item);
                if (!layout.ListItem.HasPublishedVersion) {
                    this.dataList[index].DescriptionHtml = string.Format(CultureInfo.InvariantCulture, "{0}\r\n<br/> \r\n<table>\r\n    <tr>\r\n        <td>\r\n            <img src=\"/_Layouts/images/ewr024.gif\" alt=\"{1}\"/>\r\n        </td>\r\n        <td class=\"ms-alerttext\">{2}</td>\r\n    </tr>\r\n</table>", new object[] { layout.Description, GetPublishingResourcesString("DeployStatusWarningMessageAltText"), GetPublishingResourcesString("WarningNoApprovedMasterPage") });
                } else {
                    this.dataList[index].DescriptionHtml = SPHttpUtility.HtmlEncodeAllowSimpleTextFormatting(layout.Description);
                }
                this.dataList[index].Name = layout.GetMasterPageUIDisplayName();
                if (string.IsNullOrEmpty(layout.PreviewImageUrl)) {
                    this.dataList[index].PreviewImageUrl = base.Site.GetDefaultPageLayoutPreviewImageUrl();
                } else {
                    this.dataList[index].PreviewImageUrl = layout.PreviewImageUrl;
                }
                this.dataList[index].Value = layout.ServerRelativeUrl;
                index++;
            }
        }

        private void LoadValues() {
            this.EnsureChildControls();
            this.InitDataList();
            PublishingWeb currentPublishingWeb = this.CurrentPublishingWeb;
            this.NonPostBackInitMasterPageSettingControls(currentPublishingWeb, CustomMasterPageModule.CUSTOM_MASTER_PAGE, this.inheritSystemMasterPageRadioButton, this.selectSystemMasterPageRadioButton, this.systemMasterPageSelectionControl, this.invalidSystemMasterPageWarning);
            if(this.Web.Site.WebApplication.Features[FEATURE_CustomAdminMasterPage] == null) {
                webapplicationWarning.Visible = true;
            }
        }

        private void NonPostBackInitMasterPageSettingControls(PublishingWeb area, string key, RadioButtonWithChild inheritRadioButton, RadioButtonWithChild selectRadioButton, DropDownListWithDetails pageSelectionControl, Control invalidSelectionWarning) {
            string currentSelectionValue = null;
            if (area.Web.Properties.ContainsKey(key)) {
                currentSelectionValue = area.Web.Properties[key];
            }
            pageSelectionControl.DataList = this.dataList;
            if (!string.IsNullOrEmpty(currentSelectionValue)) {
                if (!pageSelectionControl.SetSelectionByValue(currentSelectionValue)) {
                    invalidSelectionWarning.Visible = true;
                }
            }
            inheritRadioButton.Checked = string.IsNullOrEmpty(currentSelectionValue);
            selectRadioButton.Checked = !inheritRadioButton.Checked;
        }
 
        protected override void OnLoad(EventArgs e) {
            base.OnLoad(e);

            SPContext context = SPContext.GetContext(HttpContext.Current);
            this.contextPublishingWeb = PublishingWeb.GetPublishingWeb(context.Web);

            this.EnsureChildControls();
            if (!this.Page.IsPostBack) {
                this.LoadValues();
            }
            if (base.IsPostBack) {
                this.referrerUrl = this.ViewState["__PublishingUrlReferrer"] as string;
            } else {
                try {
                    if (Request.UrlReferrer != null) {
                        string str = ConcatUrls(this.contextPublishingWeb.Web.ServerRelativeUrl, "_layouts/settings.aspx");
                        this.referrerUrl = str;
                        this.ViewState["__PublishingUrlReferrer"] = this.referrerUrl;
                    }
                } catch (UriFormatException) {

                }
            }
        }

        internal static string ConcatUrls(string firstPart, string secondPart) {
            if (!firstPart.EndsWith("/", StringComparison.OrdinalIgnoreCase)) {
                if (!secondPart.StartsWith("/")) {
                    return (firstPart + "/" + secondPart);
                }
                return (firstPart + secondPart);
            }
            if (secondPart.StartsWith("/")) {
                firstPart = firstPart.TrimEnd("/".ToCharArray());
            }
            return (firstPart + secondPart);
        }

        // Properties
        protected override SPBasePermissions RightsRequired {
            get { return SPBasePermissions.ManageWeb; }
        }

        private string referrerUrl;

        private string finishUrl;
        internal virtual string FinishUrl {
            get {
                string str = SPHttpUtility.UrlPathDecode(base.Request.QueryString["Source"], false);
                if (str != null) {
                    return str;
                }
                while (this.finishUrl != null) {
                    return this.finishUrl;
                }
                return this.referrerUrl;
            }
            set { this.finishUrl = value; }
        }

        private PublishingWeb contextPublishingWeb;
        internal PublishingWeb CurrentPublishingWeb {
            get { return this.contextPublishingWeb; }
        }
    }

    public static class PublishingSiteExt {

        public static SPListItemCollection GetMasterPageLayouts(this PublishingSite psite) {
            SPQuery query = new SPQuery();
            query.ViewAttributes = "Scope=\"Recursive\"";
            query.RowLimit = 0;
            query.Query = @"
<Where>
    <And>
        <Neq><FieldRef Name='FSObjType'></FieldRef><Value Type='Integer'>1</Value></Neq>
        <Eq><FieldRef Name='File_x0020_Type'/><Value Type='Text'>master</Value></Eq>
    </And>
</Where>";
            SPDocumentLibrary layoutsDocumentLibrary = psite.Site.RootWeb.GetCatalog(SPListTemplateType.MasterPageCatalog) as SPDocumentLibrary;
            return layoutsDocumentLibrary.GetItems(query);
        }

        public static string GetDefaultPageLayoutPreviewImageUrl(this SPSite site) {
            return CommonUtility.ExpandUrlTokens("~sitecollection/_catalogs/masterpage/~language/Preview Images/DefaultPageLayout.png", site.RootWeb.ServerRelativeUrl, site.RootWeb.ServerRelativeUrl, new CultureInfo(Convert.ToInt32(site.RootWeb.Language)).Name);
        }

        public static bool GetHasPublishedVersion(this SPListItem item) {
            bool flag = false;
            foreach (SPListItemVersion current in item.Versions) {
                if (current.Level == SPFileLevel.Published) {
                    flag = true;
                }
            }
            return flag;
        }

        public static string GetMasterPageUIDisplayName(this PageLayout layout) {
            StringBuilder builder = new StringBuilder();
            string url = layout.ListItem.Url;
            int num = url.LastIndexOf('/');
            int length = layout.ListItem.ParentList.RootFolder.Url.Length;
            if (length < num) {
                builder.Append(url.Substring(length + 1, num - length));
            }
            builder.Append(layout.Name);
            return builder.ToString();
        }
    }
}